<template>
  <div class="table-container">
    <table class="table" :style="{ width: '100%', height: '100%' }">
      <thead>
        <tr>
          <th
            v-for="(column, index) in columns"
            :key="index"
            :style="[getColumnWidthStyle(column.width), { color: fontColor, borderColor: borderColor }]"
          >
            {{ column.label }}
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(row, rowIndex) in data" :key="rowIndex">
          <td
            v-for="(column, colIndex) in columns"
            :key="colIndex"
            :style="[getColumnWidthStyle(column.width), { color: fontColor, borderColor: borderColor }]"
            :title="row[column.prop]"
            class="table-cell"
          >
            {{ row[column.prop] }}
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { defineProps } from 'vue'

// 接收父级传递的列配置和数据
const props = defineProps({
  columns: {
    type: Array,
    required: true,
    default: () => []
  },
  data: {
    type: Array,
    required: true,
    default: () => []
  },
  fontColor: {
    type: String,
    default: 'black'  // 默认字体颜色为黑色
  },
  borderColor: {
    type: String,
    default: '#ddd'  // 默认边框颜色为浅灰色
  }
})

// 计算每一列的宽度
const getColumnWidthStyle = (width) => {
  return width ? `width: ${width}` : 'flex: 1'  // 如果传递了宽度则使用传递的宽度，否则自适应
}
</script>

<style scoped>
.table-container {
  width: 100%;
  height: 100%;
  overflow: auto;
}

.table {
  width: 100%;
  height: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 8px;
  text-align: left;
  border: 1px solid;
}

.table-cell {
  white-space: nowrap;  /* 防止文字换行 */
  overflow: hidden;     /* 超出部分隐藏 */
  text-overflow: ellipsis;  /* 超出显示... */
}
</style>
